<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card ref="elCard">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input clearable @clear="getUserList" placeholder="请输入内容" v-model="queryInfo.query">
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddUserDialog">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch @change="switchChange(scope.row)" v-model="scope.row.mg_state">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button @click="showEditDialog(scope.row.id)" type="primary" icon="el-icon-edit" size="mini"></el-button>
            <!-- 删除按钮 -->
            <el-button @click="removeUser(scope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button @click="showSetRoleDialog(scope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 visible.sync: 控制对话框显示隐藏：布尔值 -->
    <el-dialog
      title="添加用户"
      @close="closeAddUserDialog"
      :visible.sync="addUserDialogVisible"
      width="50%">
      <el-form 
      :model="addRuleForm" 
      :rules="addRules" 
      ref="addRuleFormRef" 
      label-width="100px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addRuleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addRuleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      @close="closeEditDialog"
      :visible.sync="editDialogVisible"
      width="50%">
      <!-- model:存储表单的数据 rules: 表单的校验规则 -->
      <el-form 
      :model="userInfo" 
      :rules="editRules" 
      ref="editRuleFormRef" 
      label-width="100px">
        <el-form-item label="用户名称">
          <el-input disabled v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      @close="setRoleClose"
      width="50%">
      <div>
        <p>当前的用户：{{users.username}}</p>
        <p>当前的角色：{{users.role_name}}</p>
        <div>
          选择新的角色：
          <el-select v-model="selectValue" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserRole">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    // 自定义验证邮箱的校验规则
    var checkEmail = (rule,value,callback)=>{
      // value: 就是要校验输入框的值
      // callback：回调函数，校验成功直接调用callback()
      //                    校验失败callback(new Error('错误信息'))
      // 邮箱的正则表达式
      var reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      // 判断邮箱格式不正确
      if(!reg.test(value)) return callback(new Error('邮箱格式不正确'))
      // 邮箱格式正确
      callback()
    }
    // 自定义验证手机号码的校验规则
    var checkMobile = (rule,value,callback)=>{
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if(!reg.test(value)) return callback(new Error('亲，您填写的手机号码格式不正确呦'))
      callback()
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      userlist: [],
      total: 0,
      addUserDialogVisible: false,
      // 添加用表的表单数据
      addRuleForm:{
        username: '',
        password: '',
        email: '',
        mobile: ''
      },

      // 添加用户表单的校验规则
      addRules:{
        username:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile:[
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      // 控制显示编辑用户对话框
      editDialogVisible: false,

      // 用户详细信息
      userInfo: {},
      editRules: {
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile:[
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      // 控制分配角色对话框的值
      setRoleDialogVisible: false,

      users:{},
      rolesList: [],

      selectValue: ''
    }
  },
  created() {
    this.getUserList()
  },
  mounted(){
    // console.log(this.$refs.mydiv.innerHTML)
    console.log(this.$refs.elCard)
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    },

    // 每页的条数发生变化会触发
    handleSizeChange(val) {
      console.log('handleSizeChange',val)
      this.queryInfo.pagesize = val
      this.getUserList()
    },

    // 页码发生变化触发
    handleCurrentChange(val) {
      // val: 最新的页码值
      console.log('handleCurrentChange',val)
      this.queryInfo.pagenum = val
      this.getUserList()
    },

    // 监听switch开关状态发生变化
    async switchChange(row) {
      console.log(row)
      // 用户id: row.id  最新状态: row.mg_state
      const {data: res} = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if(res.meta.status !== 200) return this.$message.error('修改失败')
      this.$message.success('修改成功')
    },

    // 显示添加用户对话框
    showAddUserDialog() {
      this.addUserDialogVisible = true
    },

    // 关闭对话框
    closeAddUserDialog() {
      // 通过ref获取到form表单组件，调用resetFields重置表单
      this.$refs.addRuleFormRef.resetFields()
    },

    // 添加用户
    addUser() {
      // 先校验表单是否填写完整
      // 如果填写完整，可以发送请求完成添加操作
      // 如果填写不完整，不可以发送，并且给一个提示
      this.$refs.addRuleFormRef.validate(async flag=>{
        if(!flag) return this.$message.error('亲，表单还没填写完整哦')
        // 发送请求创建用户
        const {data: res} = await this.$http.post('users',this.addRuleForm)
        // 判断status不等于201 创建失败
        if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
        // 提示创建成功
        this.$message.success('创建用户成功')
        // 关闭对话框
        this.addUserDialogVisible = false 
        // 重新获取用户列表数据
        this.getUserList()
      })
    },

    // 显示编辑用户对话框
    async showEditDialog (id) {
      // 根据id获取到用户详细信息
      const {data: res} = await this.$http(`users/${id}`)
      if(res.meta.status !== 200) return this.$message.error('查询失败')
      this.userInfo = res.data
      this.editDialogVisible = true
    },

    closeEditDialog() {
      // 获取到表单调用resetFields
      this.$refs.editRuleFormRef.resetFields()
    },

    // 修改用户提交
    editUser() {
      // 首先要校验整个表单是否校验成功
      this.$refs.editRuleFormRef.validate(async flag=>{
        if(!flag) return this.$message.error('亲，请完善表单信息')
        // 发送修改用户的请求
        const {data: res} = await this.$http.put(`users/${this.userInfo.id}`,{
          email: this.userInfo.email,
          mobile: this.userInfo.mobile
        })

        // 更新失败
        if(res.meta.status !== 200) return this.$message.error('更新失败')
        
        // 更新成功
        this.editDialogVisible = false 
        this.getUserList()
        this.$message.success('更新成功')
      })
    },

    // 删除用户
    removeUser(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点击确定删除
        const {data: res} = await this.$http.delete(`users/${id}`)

        if(res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getUserList()

      }).catch(() => {
        // 点击取消
        this.$message('取消删除')         
      });
    },

    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if(res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.rolesList = res.data
    },
    // 显示分配角色对话框
    showSetRoleDialog(row) {
      this.users = row
      this.setRoleDialogVisible = true
      this.getRolesList()
    },

    // 分配用户角色
    async setUserRole() {
      if(this.selectValue === '') return this.$message.error('亲，请选择角色哦')
      const { data: res } = await this.$http.put(`users/${this.users.id}/role`,{
        rid: this.selectValue
      })
      console.log(res)
      if(res.meta.status !== 200) return this.$message.error('分配失败')
      this.$message.success('分配成功')
      this.setRoleDialogVisible = false
      this.getUserList()
    },

    // 关闭分配角色对话框
    setRoleClose() {
      this.selectValue = ''
    }
  }
}
</script>

<style lang="less" scoped>
</style>
